package com.mysiteforme.admin.controller.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mysiteforme.admin.dao.DictDao;
import com.mysiteforme.admin.dao.ElectricityCompanyDao;
import com.mysiteforme.admin.dao.ElectricityUserDao;
import com.mysiteforme.admin.entity.*;
import com.mysiteforme.admin.service.*;
import com.mysiteforme.admin.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mysiteforme.admin.util.LayerData;
import com.mysiteforme.admin.util.RestResponse;
import com.mysiteforme.admin.annotation.SysLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表  前端控制器
 * </p>
 *
 * @author wangl
 * @since 2019-09-18
 */
@Controller
@RequestMapping("/admin/electricityUser")
public class ElectricityUserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ElectricityUserController.class);

    @Autowired
    private ElectricityUserService electricityUserService;
    @Autowired
    private ElectricityUserDao electricityUserDao;
    @Autowired
    private ElectricityCompanyService electricityCompanyService;
    @Autowired
    private ElectricityCompanyDao electricityCompanyDao;
    @Autowired
    private ElectricityAreaService areaService;
    @Autowired
    private ElectricityMessagePushService electricityMessagePushService;
    @Autowired
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    @Autowired
    private DictDao dictDao;


    @GetMapping("list")
    @SysLog("跳转用户信息表列表")
    public String list() {
        return "/admin/electricityUser/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求用户信息表列表数据")
    public LayerData<ElectricityUser> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                           ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "s_");

        LayerData<ElectricityUser> layerData = new LayerData<>();
        Integer total;
        List<ElectricityUser> records;
        String userId = (String) map.get("userId");
        String userName = (String) map.get("userName");
        String phone = (String) map.get("phone");
        String memberType = (String) map.get("memberType");
        String startTime = (String) map.get("startTime");
        String endTime = (String) map.get("endTime");
        String isDelete = (String) map.get("isDelete");
        String isCheck = (String) map.get("isCheck");
        if (!map.isEmpty()) {
            records = electricityUserDao.selectPageLists(page, limit, userId, userName, phone, memberType, startTime, endTime, isDelete, isCheck);
            total = electricityUserDao.getCounts(userId, userName, phone, memberType, startTime, endTime, isDelete, isCheck);
        } else {
            records = electricityUserDao.selectPageList(page, limit);
            total = electricityUserDao.getCount();
        }
        for (ElectricityUser electricityUser : records) {
            electricityUser.setUserId(String.valueOf(electricityUser.getId()));
        }
        layerData.setData(records);

        layerData.setCount(total);
        return layerData;
    }

    @GetMapping("add")
    @SysLog("跳转新增用户信息表页面")
    public String add() {
        return "/admin/electricityUser/add";
    }

    @PostMapping("add")
    @SysLog("保存新增用户信息表数据")
    @ResponseBody
    public RestResponse add(ElectricityUser electricityUser) {
        electricityUserService.insert(electricityUser);
        return RestResponse.success();
    }

    @GetMapping("edit")
    @SysLog("跳转编辑用户信息表页面")
    public String edit(Long id, Model model) {
        ElectricityUser electricityUser = electricityUserService.selectById(id);

        EntityWrapper<ElectricityCompany> companyWrapper = new EntityWrapper<>();
        companyWrapper.eq("user_id", id);
        ElectricityCompany company = electricityCompanyService.selectOne(companyWrapper);

        if (company != null) {
            if (company.getBusinessProvince() != null && company.getBusinessCity() != null && company.getBusinessCountry() != null) {
                model.addAttribute("businessProvince", company.getBusinessProvince());
                model.addAttribute("businessCity", company.getBusinessCity());
                model.addAttribute("businessCountry", company.getBusinessCountry());

                String areaName = electricityCompanyDao.getNameById(company.getBusinessProvince());
                model.addAttribute("businessProvinceName", areaName);
                areaName = electricityCompanyDao.getNameById(company.getBusinessCity());
                model.addAttribute("businessCityName", areaName);
                areaName = electricityCompanyDao.getNameById(company.getBusinessCountry());
                model.addAttribute("businessCountryName", areaName);
            }
            model.addAttribute("electricityCompany", company);
        }
        model.addAttribute("electricityUser", electricityUser);

        return "/admin/electricityUser/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑用户信息数据")
    public RestResponse edit(ElectricityUser electricityUser, ElectricityCompany electricityCompany) {
        if (null == electricityUser.getId() || 0 == electricityUser.getId()) {
            return RestResponse.failure("ID不能为空");
        }

        electricityUserService.updateById(electricityUser);
        EntityWrapper<ElectricityCompany> companyWrapper = new EntityWrapper<>();
        companyWrapper.eq("user_id", electricityUser.getId());

        electricityCompany.setIsDelete("1");
        electricityCompany.setDueDate(electricityCompany.getDueDate());
        electricityCompanyService.update(electricityCompany, companyWrapper);
        return RestResponse.success();
    }

    /**
     * 获取所有地区
     */
    @SysLog("获取所有地区")
    @PostMapping("/getAllArea")
    @ResponseBody
    public JSONArray goodsClassAll() {
        EntityWrapper<ElectricityArea> areaQuery = new EntityWrapper<ElectricityArea>();
        areaQuery.ne("id", "1");
        List<ElectricityArea> selectList = areaService.selectList(areaQuery);
        JSONArray array = new JSONArray();
        setPermissionsTree(0, selectList, array);
        return array;
    }

    /**
     * 菜单树
     *
     * @param pId
     * @param permissionsAll
     * @param array
     */
    private void setPermissionsTree(Integer pId, List<ElectricityArea> permissionsAll, JSONArray array) {
        for (ElectricityArea a : permissionsAll) {
            if ((pId == 0 && a.getParentId() == null) || (a.getParentId() != null && a.getParentId().intValue() == pId.intValue())) {
                String string = JSONObject.toJSONString(a, SerializerFeature.IgnoreNonFieldGetter);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);

                if (permissionsAll.stream().filter(p -> p.getParentId() != null && p.getParentId() == a.getId().intValue()).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(a.getId().intValue(), permissionsAll, child);
                }
            }
        }
    }

    @GetMapping("view")
    @SysLog("跳转查看用户信息表页面")
    public String view(String id, Model model) {
        ElectricityUser electricityUser = electricityUserService.selectById(id);

        EntityWrapper<ElectricityCompany> companyWrapper = new EntityWrapper<>();
        companyWrapper.eq("user_id", id);
        ElectricityCompany company = electricityCompanyService.selectOne(companyWrapper);
        model.addAttribute("electricityCompany", company);

        if (company != null) {
            if (company.getBusinessProvince() != null && company.getBusinessCity() != null && company.getBusinessCountry() != null) {
                model.addAttribute("businessProvince", company.getBusinessProvince());
                model.addAttribute("businessCity", company.getBusinessCity());
                model.addAttribute("businessCountry", company.getBusinessCountry());

                String areaName = electricityCompanyDao.getNameById(company.getBusinessProvince());
                model.addAttribute("businessProvinceName", areaName);
                areaName = electricityCompanyDao.getNameById(company.getBusinessCity());
                model.addAttribute("businessCityName", areaName);
                areaName = electricityCompanyDao.getNameById(company.getBusinessCountry());
                model.addAttribute("businessCountryName", areaName);
            }
            model.addAttribute("electricityCompany", company);
        }
        model.addAttribute("electricityUser", electricityUser);
        return "/admin/electricityUser/view";
    }

    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除用户")
    public RestResponse delete(@RequestParam(value = "id", required = false) Long id) {
        if (null == id || 0 == id) {
            return RestResponse.failure("ID不能为空");
        }
        ElectricityUser electricityUser = electricityUserService.selectById(id.toString());
        electricityUser.setDelFlag(true);
        electricityUserService.updateById(electricityUser);
        return RestResponse.success();
    }


    @PostMapping("pullBlack")
    @ResponseBody
    @SysLog("拉黑用户")
    public RestResponse pullBlack(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "type", required = false) String type) {
        if (null == id || 0 == id) {
            return RestResponse.failure("ID不能为空");
        }
        EntityWrapper<ElectricityCompany> companyEntityWrapper = new EntityWrapper<>();
        companyEntityWrapper.eq("user_id", id);
        ElectricityCompany company = electricityCompanyService.selectOne(companyEntityWrapper);
        company.setIsDelete(type);
        electricityCompanyService.updateById(company);
        return RestResponse.success();
    }

    @PostMapping("calPullBlack")
    @ResponseBody
    @SysLog("取消拉黑用户")
    public RestResponse calPullBlack(@RequestParam(value = "id", required = false) Long id) {
        if (null == id || 0 == id) {
            return RestResponse.failure("ID不能为空");
        }
        EntityWrapper<ElectricityCompany> companyEntityWrapper = new EntityWrapper<>();
        companyEntityWrapper.eq("user_id", id.toString());
        ElectricityCompany company = electricityCompanyService.selectOne(companyEntityWrapper);
        if(company.getIsCheck()==null||company.getIsCheck().equals("")) {
            company.setIsDelete("3");
        }else if(company.getIsCheck().equals("1")){
            company.setIsDelete("1");
        }
        electricityCompanyService.updateById(company);
        return RestResponse.success();
    }

    @PostMapping("checkPass")
    @ResponseBody
    @SysLog("审核通过")
    public RestResponse checkPass(@RequestParam(value = "id", required = false) Long id) {
        if (null == id || 0 == id) {
            return RestResponse.failure("ID不能为空");
        }
        EntityWrapper<ElectricityCompany> companyEntityWrapper = new EntityWrapper<>();
        companyEntityWrapper.eq("user_id", id.toString());
        ElectricityCompany company = electricityCompanyService.selectOne(companyEntityWrapper);

        company.setIsCheck("1");
        company.setPerfectDate(new Date());
        electricityCompanyService.updateById(company);
//        electricityMessagePushService.insertMessage(company,id);

        return RestResponse.success();
    }

    @PostMapping("refuse")
    @ResponseBody
    @SysLog("审核拒绝")
    public RestResponse refuse(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "refuseMsg", required = false) String refuseMsg) {
        if (null == id || 0 == id) {
            return RestResponse.failure("ID不能为空");
        }
        if (null == refuseMsg) {
            return RestResponse.failure("拒绝理由不能为空");
        }
        EntityWrapper<ElectricityCompany> companyEntityWrapper = new EntityWrapper<>();
        companyEntityWrapper.eq("user_id", id.toString());
        ElectricityCompany company = electricityCompanyService.selectOne(companyEntityWrapper);

        company.setIsCheck("2");
        company.setRefuseMsg(refuseMsg);
        electricityCompanyService.updateById(company);
//        electricityMessagePushService.insertMessage(company,id);
        return RestResponse.success();
    }

    @PostMapping("changePwd")
    @SysLog("用户修改密码")
    @ResponseBody
    public RestResponse changePwd(@RequestParam(value = "id",required = false)String id){
        if(StringUtils.isBlank(id)){
            return RestResponse.failure("id不能为空");
        }
        ElectricityUser user = electricityUserService.selectById(id);
        user.setUpdateDate(new Date());
        String pwd = dictDao.getByType(Constants.PASSWORD_TYPE);
        user.setPassword(passwordEncoder().encode(pwd));
        electricityUserService.updateById(user);
        return RestResponse.success();
    }

}